package com.gz.logistics.app;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gz.logistics.R;
import com.gz.logistics.library.IAuthor;
import com.gz.logistics.library.IOrder;
import com.gz.logistics.library.listener.GetQRCodeOrderDetailListener;
import com.gz.logistics.library.listener.SingleOrderDeliveryStatusChangeListener;
import com.gz.logistics.library.listener.SingleOrderLoggisticsStatusChangeListener;
import com.gz.logistics.library.pojo.OrderInfo;
import com.gz.logistics.library.pojo.ProductInfo;
import com.gz.logistics.library.pojo.UserInfo;
import com.gz.logistics.library.util.Constants;
import com.gz.logistics.library.util.PreferenceModel;
import com.gz.logistics.util.ToastUtils;
import com.gz.logistics.widget.LoadingCover;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 扫描二维码 识别出订单编号后，跳转到的订单详情界面！
 * 马丹啊！本来可以和之前的详情界面共用的！ but 之前设计没有考虑到啊啊啊啊啊啊 啊
 * author wanner1991
 */
public class QRCoderOrdeActivity extends BaseActivity implements LoadingCover.OnLoadingCoverRefreshListener, View.OnClickListener {
    private String TAG = QRCoderOrdeActivity.class.getSimpleName();
    private OrderInfo ClickOrder;//需要显示的订单
    private ImageView iv_action_back;
    private TextView tv_actionbar_title;
    private TextView tv_actionbar_deliveryName;
    private TextView tv_order_number;
    private TextView tv_create_time;
    private TextView tv_receiver_name;
    private TextView tv_receiver_phone;
    private TextView tv_receiver_address;

    private TextView tv_receiver_cpucbt; //提货方式
    private TextView tv_pay_type;  // 支付方式
    private TextView tv_money;  // 应收金额
    private TextView tv_notes;  // 备注

    private LinearLayout productList;
    private TextView tv_order_price;
    private TextView tv_logistic_status;
    private TextView tv_delivery_status;
    private Button btn_logistics_confirm;
    private Button btn_delivery_confirm;
    private Dialog mLoadingData;
    private LoadingCover mLoadingCover;

    private UserInfo userInfo;
    private String  sn ;
    private MySingleOrderLoggisticsStatusChangeListener mSingleOrderLoggisticsStatusChangeListener;
    private MySingleOrderDeliveryStatusChangeListener mSingleOrderDeliveryStatusChangeListener;
    private MyGetQRCodeOrderDetailListener mGetQRCodeOrderDetailListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qrcoder_order_detail);
        mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        mActionBar.setCustomView(R.layout.common_head_layout);//自定义ActionBar布局
        initView();
        sn = this.getIntent().getStringExtra("sn");
        initListener();
        onLoadingCoverRefresh();
    }

    @Override
    public void finish() {
        // 更新首页数据
        Intent broastIntent = new Intent(Define.ACTION_REFRESH_HOME);
        sendBroadcast(broastIntent);
        super.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSingleOrderLoggisticsStatusChangeListener.release();
        mSingleOrderDeliveryStatusChangeListener.release();
        mGetQRCodeOrderDetailListener.release();

    }

    private void initView() {
        iv_action_back = (ImageView) this.findViewById(R.id.iv_actionbar_up);
        tv_actionbar_title = (TextView) this.findViewById(R.id.tv_actionbar_title);
        tv_actionbar_deliveryName = (TextView) this.findViewById(R.id.tv_actionbar_deliveryName);

        tv_order_number = (TextView) this.findViewById(R.id.tv_order_number);
        tv_create_time = (TextView) this.findViewById(R.id.tv_create_time);
        tv_receiver_name = (TextView) this.findViewById(R.id.tv_receiver_name);
        tv_receiver_phone = (TextView) this.findViewById(R.id.tv_receiver_phone);
        tv_receiver_address = (TextView) this.findViewById(R.id.tv_receiver_address);
        tv_receiver_cpucbt = (TextView) this.findViewById(R.id.tv_receiver_cpucbt);
        tv_pay_type = (TextView) this.findViewById(R.id.tv_pay_type);
        tv_money = (TextView) this.findViewById(R.id.tv_money);
        tv_notes = (TextView) this.findViewById(R.id.tv_notes);


        productList = (LinearLayout) this.findViewById(R.id.list_products);
        tv_order_price = (TextView) this.findViewById(R.id.tv_order_price);
        tv_logistic_status = (TextView) this.findViewById(R.id.tv_logistic_status);
        tv_delivery_status = (TextView) this.findViewById(R.id.tv_delivery_status);

        btn_logistics_confirm = (Button) this.findViewById(R.id.btn_logistics_confirm);
        btn_delivery_confirm = (Button) this.findViewById(R.id.btn_delivery_confirm);
        mLoadingCover = (LoadingCover) this.findViewById(R.id.layout_loading_cover);

        mLoadingData = new Dialog(this,R.style.DialogTheme);
        mLoadingData.setContentView(R.layout.loading_data_dialog2);
        mLoadingData.setCanceledOnTouchOutside(false);
        mLoadingData.setCancelable(false);

        tv_actionbar_title.setText("订单详情");
        userInfo =  IAuthor.getInstance().loadUserInfoSyn(PreferenceModel.getInt(Constants.PREFERENCE_USER_ID, -1));
        if (userInfo != null){
            tv_actionbar_deliveryName.setText("配送员："+userInfo.getUser_name());
        }

    }

    private void initListener() {
        iv_action_back.setOnClickListener(this);
        btn_delivery_confirm.setOnClickListener(this);
        btn_logistics_confirm.setOnClickListener(this);
        mSingleOrderLoggisticsStatusChangeListener = new MySingleOrderLoggisticsStatusChangeListener(this);
        mSingleOrderDeliveryStatusChangeListener = new MySingleOrderDeliveryStatusChangeListener(this);
        mGetQRCodeOrderDetailListener = new MyGetQRCodeOrderDetailListener(this);
        mLoadingCover.setOnLoadingCoverRefreshListener(this);

    }

    private void initData() {
        if (ClickOrder == null) {
            return;
        }
        tv_order_number.setText("编号：" + ClickOrder.getSn());
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd HH:mm");
        tv_create_time.setText(format.format(new Date(ClickOrder.getCreate_at() * 1000)));
        tv_receiver_name.setText("收货人姓名：" + ClickOrder.getReceiver_name());
        tv_receiver_phone.setText("收货人电话：" + ClickOrder.getReceiver_tel());
        tv_receiver_address.setText("收货人地址：" + ClickOrder.getReceiver_add());
        String cpucbtType = ClickOrder.getCpucbt() == Define.FLAG_CPUCBT_DELIVERY ? "送货上门" : "自取";
        String payType = ClickOrder.getPay_type() == Define.FLAG_PAY_TYPE_ONLINE ? "在线支付" : "货到付款";
        tv_receiver_cpucbt.setText("提货方式：" + cpucbtType);
        tv_pay_type.setText("支付方式：" + payType);
        tv_money.setText("应收金额：￥" + ClickOrder.getMoney());
        tv_notes.setText("备注：" + ClickOrder.getNotes());
        tv_order_price.setText("￥" + ClickOrder.getMoney());

        String logistic_status = ClickOrder.getTrans_status() == Define.FLAG_TRANS_STATUS_SIGNED ? "已签收" : "未签收";
        String deliver_status = ClickOrder.getSign_status() == Define.FLAG_DELEVERY_STATUS_SIGNED ? "已签收" : "未签收";
        tv_logistic_status.setText(logistic_status);
        tv_delivery_status.setText(deliver_status);


        if (ClickOrder.getTrans_status() == Define.FLAG_TRANS_STATUS_NO_SIGN) {
            // 如果还未进行物流签收，则把"物流"置为可见,"业务签收"按钮置为不可见,
            btn_logistics_confirm.setVisibility(View.VISIBLE);
            btn_delivery_confirm.setVisibility(View.INVISIBLE);
        } else {
            // 如果已经物流签收了,"物流"置为不可见
            btn_logistics_confirm.setVisibility(View.INVISIBLE);
            if (ClickOrder.getSign_status() == Define.FLAG_DELEVERY_STATUS_SIGNED) {
                //如果业务也签收了，物流按钮 置为不可见
                btn_delivery_confirm.setVisibility(View.INVISIBLE);
            } else {
                // 业务还未签收，"业务"置为可见
                btn_delivery_confirm.setVisibility(View.VISIBLE);
            }

        }

        // 生成产品条目列表
        List<ProductInfo> products = ClickOrder.getProductInfos();
        productList.removeAllViews();
        for (int j = 0; j < products.size(); j++) {
            ProductInfo productInfo = products.get(j);

            View productItemView = LayoutInflater.from(this).inflate(R.layout.home_orders_products_item, null);
            TextView tv_product_name = (TextView) productItemView.findViewById(R.id.tv_product_name);
            TextView tv_total_price = (TextView) productItemView.findViewById(R.id.tv_total_price);

            tv_product_name.setText(productInfo.getProduct_name());

            tv_total_price.setText(productInfo.getProduct_num() + " × " + productInfo.getProduct_price());

            productList.addView(productItemView);
        }
    }

    @Override
    public void onLoadingCoverRefresh() {
        IOrder.getInstance().getQRCodeOrderDetail(sn,mGetQRCodeOrderDetailListener);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_actionbar_up:
                finish();
                break;
            case R.id.btn_delivery_confirm:
                mLoadingData.show();
                if (ClickOrder != null){
                   // IOrder.getInstance().singalorderDeliveryStatusSign(ClickOrder.getSn(),mSingleOrderDeliveryStatusChangeListener);
                }
                break;
            case R.id.btn_logistics_confirm:
                mLoadingData.show();
                if (ClickOrder != null){
                    IOrder.getInstance().singalorderLogisticsStatusSign(ClickOrder.getSn(),mSingleOrderLoggisticsStatusChangeListener);
                }
                break;
        }

    }

    /**
     * 获取订单详情监听器
     */
    private static class MyGetQRCodeOrderDetailListener extends GetQRCodeOrderDetailListener{
        private QRCoderOrdeActivity mOuter;

        public MyGetQRCodeOrderDetailListener(QRCoderOrdeActivity mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){

            new WeakReference<QRCoderOrdeActivity>(mOuter);
        }

        @Override
        public void onOrderInfoNotExist() {
            mOuter.mLoadingCover.onRefreshFailed("订单信息不存在");
            ToastUtils.showToast(mOuter,"订单信息不存在");
        }

        @Override
        public void onNotBelongToThisUser() {
            mOuter.mLoadingCover.onRefreshFailed("该订单不属于当前用户");
            ToastUtils.showToast(mOuter,"该订单不属于当前用户");

        }

        @Override
        public void onResponseSuccess(OrderInfo orderDetail) {
            mOuter.ClickOrder = orderDetail;
            mOuter.initData();
            mOuter.mLoadingCover.onRefreshSuccess();

        }

        @Override
        public void onNoNetWork() {
            mOuter.mLoadingCover.onRefreshFailed(Define.MSG_NO_NETWORK);

        }

        @Override
        public void onResponseFailed() {
            mOuter.mLoadingCover.onRefreshFailed("请求失败" );
        }
    }

    /**
     * 单订单物流签收 回调接口
     */
    private static class MySingleOrderLoggisticsStatusChangeListener extends SingleOrderLoggisticsStatusChangeListener{
        private QRCoderOrdeActivity mOuter;

        public MySingleOrderLoggisticsStatusChangeListener(QRCoderOrdeActivity mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<QRCoderOrdeActivity>(mOuter);
        }

        @Override
        public void onResponseSuccess() {
            mOuter.btn_logistics_confirm.setVisibility(View.INVISIBLE);
            mOuter.btn_delivery_confirm.setVisibility(View.VISIBLE);
            mOuter.tv_logistic_status.setText("已签收");
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter.getApplicationContext(), "物流签收成功");



        }

        @Override
        public void onNoNetWork() {
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter.getApplicationContext(),Define.MSG_NO_NETWORK);

        }

        @Override
        public void onResponseFailed() {
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter.getApplicationContext(),"物流签收失败");
        }
    }

    /**
     * 单订单业务签收回调接口
     */
    private class MySingleOrderDeliveryStatusChangeListener extends  SingleOrderDeliveryStatusChangeListener{
        private QRCoderOrdeActivity mOuter;

        public MySingleOrderDeliveryStatusChangeListener(QRCoderOrdeActivity mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<QRCoderOrdeActivity>(mOuter);
        }

        @Override
        public void onHasNotSignLogistic() {
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter.getApplicationContext(),"请先完成该订单的物流签收");

        }

        @Override
        public void onResponseSuccess() {
            mOuter.btn_logistics_confirm.setVisibility(View.INVISIBLE);
            mOuter.btn_delivery_confirm.setVisibility(View.INVISIBLE);
            mOuter.tv_delivery_status.setText("已签收");
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter.getApplicationContext(), "业务签收成功");


        }

        @Override
        public void onNoNetWork() {
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter.getApplicationContext(), Define.MSG_NO_NETWORK);

        }

        @Override
        public void onResponseFailed() {
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter.getApplicationContext(), "业务签收失败");
        }
    }

}
